package com.china.produce.pojo;

import com.china.produce.system.util.ServerLongPollingUtil;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/12/27
 */
public class ClientLongPolling implements Runnable{

    Future<?> asyncTimeoutFuture;

    public AsyncContext asyncContext;

    public String groupKey;

    public Long timeout;

    public ClientLongPolling(AsyncContext asyncContext, String groupKey, Long timeout) {
        this.asyncContext = asyncContext;
        this.groupKey = groupKey;
        this.timeout = timeout;
    }

    @Override
    public void run() {
        asyncTimeoutFuture =  ServerLongPollingUtil.scheduleLongPolling(new Runnable() {
            @Override
            public void run() {
                ServerLongPollingUtil.allSubs.remove(ClientLongPolling.this);
                sendResponse(null);
            }
        }, timeout, TimeUnit.MILLISECONDS);

        //添加到阻塞队列
        ServerLongPollingUtil.allSubs.add(this);
    }

    void sendResponse(String changedGroups) {
        if (null != asyncTimeoutFuture) {
            asyncTimeoutFuture.cancel(false);
        }

        generateResponse(changedGroups);
    }

    void generateResponse(String groupKey) {
        if(null == groupKey) {
            asyncContext.complete();
            return;
        }

        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

        try{
            String res = ServerLongPollingUtil.configMap.get(groupKey);
            response.setHeader("Pargma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache, no-store");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(res);
            asyncContext.complete();
        }catch (Exception ex) {
            asyncContext.complete();
        }
    }
}
